import 'dart:convert';
import 'package:flutter/material.dart';
import './client_dio.dart';
import './items.dart';
import './login_screen.dart';
import './packs.dart';

class BS4App extends StatefulWidget {
  const BS4App({Key? key}) : super(key: key);

  @override
  State<BS4App> createState() => _BS4AppState();
}

class _BS4AppState extends State<BS4App> {
  bool _darkMode = false;
  bool _loggedIn = false;
  bool _showLoginDialog = false;
  bool _showEditDialog = false;
  String _user = 'AnonymousUser';
  List<String> _users = [];
  List<Map<String, dynamic>> _contacts = [];
  int _start = 0;
  int _limit = 15;
  int _total = 0;
  String _search = '';
  int _startInput = 1;
  String _baoxiang = '';
  Map<String, dynamic>? _selectedContact;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  void _loadData() {
    // 使用实际API加载数据
    contacts(
      {
        'start': _start,
        'limit': _limit,
        'search': _search,
        'baoxiang': _baoxiang,
      },
      (contacts) {
        setState(() {
          // 确保contacts['data']是列表类型，如果不是则使用空列表
          List<dynamic> dataList = (contacts['data'] is List) ? contacts['data'] : [];
          _contacts = dataList
              .where((item) => item is Map<String, dynamic>)
              .map((item) => item as Map<String, dynamic>)
              .toList();
          _total = contacts['total'] ?? dataList.length;
          _user = (contacts['user'] ?? 'AnonymousUser').trim();
          // Load users from API response if available
          if (contacts['users'] is List) {
            _users = List<String>.from(contacts['users']);
          } else if (_users.isEmpty) {
            // Fallback to mock data if API doesn't provide users list and _users is empty
            _users = ['user1', 'user2', 'user3']; // 临时模拟数据
          }
          // Ensure the current user is in the users list to avoid DropdownButton errors
          if (!_users.contains(_user)) {
            _users.add(_user);
          }
        });
      },
      (error) {
        print('加载数据失败: $error');
        // 如果是登录错误，显示登录对话框
        // if (error is...) 
        setState(() {
          _showLoginDialog = true;
        });
      },
    );
  }

  void _toggleTheme() {
    setState(() {
      _darkMode = !_darkMode;
      // Save theme to local storage
      // SharedPreferences.getInstance().then((prefs) {
      //   prefs.setBool('darkMode', _darkMode);
      // });
    });
  }

  void _handleLogout() {
    logout((r) {
      setState(() {
        _loggedIn = false;
        _user = 'AnonymousUser';
        _contacts = [];
        _total = 0;
        _start = 0;
      });
    });
  }

  void _handleSearchChange(String value) {
    setState(() {
      _search = value;
    });
  }

  void _performSearch() {
    setState(() {
      _start = 0;
    });
    _loadData();
  }

  void _handlePrev() {
    setState(() {
      if (_start > 0) {
        _start -= _limit;
        _loadData();
      }
    });
  }

  void _handleNext() {
    setState(() {
      if (_start + _limit < _total) {
        _start += _limit;
        _loadData();
      }
    });
  }

  void _handlePageChange(String value) {
    setState(() {
      _startInput = int.tryParse(value) ?? 1;
    });
  }

  void login_click() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => LoginScreen()),
    );
    if (result != null) {
      setState(() {
        _loggedIn = true;
        _user = result['user'] ?? 'AnonymousUser';
        if (!_users.contains(_user)) {
          _users.add(_user);
        }
      });
      _loadData();
    }
  }
  
  void _jump() {
    setState(() {
      final int page = _startInput;
      if (page > 0) {
        _start = (page - 1) * _limit;
        _loadData();
      }
    });
  }

  void _onDetailClick(Map<String, dynamic> contact) {
    setState(() {
      _selectedContact = contact;
    });
  }

  void _handleContactChange(int? index, Map<String, dynamic> newContact) {
    setState(() {
      if (index != null && index < _contacts.length) {
        _contacts[index] = newContact;
      } else {
        _contacts.add(newContact);
        _total++;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(
        brightness: _darkMode ? Brightness.dark : Brightness.light,
        primarySwatch: Colors.blue,
      ),
      child: Scaffold(
        body: SafeArea(
          child: Container(
            padding: EdgeInsets.all(20.0),
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[

                  // 菜单按钮
                  Container(
                    margin: EdgeInsets.only(bottom: 20.0),
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: [
                          if (!_loggedIn) ...[
                            ElevatedButton.icon(
                              icon: Icon(Icons.login),
                              label: Text('登录'),
                              onPressed: login_click,
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.blue.shade400,
                                foregroundColor: Colors.white,
                                padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                              ),
                            ),
                            SizedBox(width: 10),
                          ],
                          if (_loggedIn) ...[
                            Text(
                              _user,
                              style: TextStyle(
                                fontSize: 18,
                                color: _darkMode ? Colors.white : Colors.black,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            SizedBox(width: 20),
                            ElevatedButton.icon(
                              icon: Icon(Icons.logout),
                              label: Text('登出'),
                              onPressed: _handleLogout,
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.blue.shade400,
                                foregroundColor: Colors.white,
                                padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                              ),
                            ),
                            SizedBox(width: 10),
                          ],
                                                    ElevatedButton.icon(
                            icon: Icon(Icons.shopping_bag),
                            label: Text('包'),
                            onPressed: () async {
                              await Navigator.push(
                                context,
                                MaterialPageRoute(builder: (context) => PacksHome()),
                              );
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue.shade400,
                              foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),

                          SizedBox(width: 10),
                          ElevatedButton.icon(
                            icon: Icon(Icons.inventory),
                            label: Text('备件'),
                            onPressed: () {
                              Navigator.of(context).push(
                                MaterialPageRoute(
                                  builder: (context) => ItemsHome(),
                                ),
                              );
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue.shade400,
                              foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          ElevatedButton.icon(
                            icon: Icon(Icons.copy),
                            label: Text('复制包'),
                            onPressed: () {},
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue.shade400,
                              foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          ElevatedButton.icon(
                            icon: Icon(Icons.analytics),
                            label: Text('统计'),
                            onPressed: () {},
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue.shade400,
                              foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          ElevatedButton.icon(
                            icon: Icon(Icons.calendar_today),
                            label: Text('工作量'),
                            onPressed: () {},
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue.shade400,
                              foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          ElevatedButton.icon(
                            icon: Icon(Icons.home),
                            label: Text('home'),
                            onPressed: () {},
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue.shade400,
                              foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                          ),
                          SizedBox(width: 10),
                          ElevatedButton.icon(
                            icon: Icon(Icons.admin_panel_settings),
                            label: Text('admin'),
                            onPressed: () {},
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue.shade400,
                              foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),

                  // 用户下拉菜单和搜索框
                  Container(
                    margin: EdgeInsets.only(bottom: 20.0),
                    padding: EdgeInsets.all(12.0),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8.0),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.1),
                          spreadRadius: 1,
                          blurRadius: 3,
                          offset: Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Row(
                      children: [
                        DropdownButton<String>(
                          value: _user,
                          items: [
                            const DropdownMenuItem(
                              value: 'AnonymousUser',
                              child: Text('AnonymousUser'),
                            ),
                            ..._users.toSet().where((user) => user != 'AnonymousUser').map((user) => DropdownMenuItem(
                                  value: user,
                                  child: Text(user),
                                )),
                          ],
                          onChanged: (value) {
                            if (value != null) {
                              setState(() {
                                _user = value;
                                _loggedIn = value != 'AnonymousUser';
                                if (_loggedIn) {
                                  _loadData();
                                }
                              });
                            }
                          },
                        ),
                        const SizedBox(width: 20),
                        Expanded(
                          child: TextField(
                            onChanged: _handleSearchChange,
                            onSubmitted: (value) => _performSearch(),
                            decoration: InputDecoration(
                              hintText: '合同 or 仪器编号 or 客户',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                              prefixIcon: Icon(Icons.search),
                              contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0),
                            ),
                          ),
                        ),
                        const SizedBox(width: 20),
                        ElevatedButton.icon(
                          icon: Icon(Icons.search),
                          label: Text('搜索'),
                          onPressed: _performSearch,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue.shade600,
                            foregroundColor: Colors.white,
                            padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 14.0),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 操作按钮
                  Container(
                    margin: EdgeInsets.only(bottom: 20.0),
                    child: Row(
                      children: [
                        ElevatedButton.icon(
                          icon: Icon(Icons.add),
                          label: Text('新仪器'),
                          onPressed: () {
                            setState(() {
                              _showEditDialog = true;
                            });
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green.shade600,
                            foregroundColor: Colors.white,
                            padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 14.0),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        ElevatedButton.icon(
                          icon: Icon(Icons.upload_file),
                          label: Text('导入标样'),
                          onPressed: () {},
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.orange.shade600,
                            foregroundColor: Colors.white,
                            padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 14.0),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 联系人列表
                  Container(
                    margin: EdgeInsets.only(bottom: 20.0),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.0),
                      border: Border.all(color: Colors.blue.shade200, width: 1.0),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.1),
                          spreadRadius: 1,
                          blurRadius: 3,
                          offset: Offset(0, 2),
                        ),
                      ],
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8.0),
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: DataTable(
                          columns: const [
                            DataColumn(label: Text('ID')),
                            DataColumn(label: Text('客户单位')),
                            DataColumn(label: Text('客户地址')),
                            DataColumn(label: Text('合同编号')),
                            DataColumn(label: Text('仪器编号')),
                            DataColumn(label: Text('仪器型号')),
                            DataColumn(label: Text('通道配置')),
                            DataColumn(label: Text('包箱')),
                            DataColumn(label: Text('入库时间')),
                            DataColumn(label: Text('方法')),
                          ],
                          rows: _contacts
                              .map((contact) => DataRow(cells: [
                                    DataCell(Text(contact['id'].toString())),
                                    DataCell(Text(contact['yonghu'] ?? '')), // 客户单位
                                    DataCell(Text(contact['addr'] ?? '')), // 客户地址
                                    DataCell(Text(contact['hetongbh'] ?? '')), // 合同编号
                                    DataCell(Text(contact['yiqibh'] ?? '')), // 仪器编号
                                    DataCell(Text(contact['yiqixinghao'] ?? '')), // 仪器型号
                                    DataCell(Text(contact['channels'] ?? '')), // 通道配置
                                    DataCell(Text(contact['baoxiang'] ?? '')), // 包箱
                                    DataCell(Text(contact['tiaoshi_date'] ?? contact['yujifahuo_date'] ?? '')), // 入库时间（调试日期或预计发货日期）
                                    DataCell(Text(contact['method'] ?? '')), // 方法
                                  ], onSelectChanged: (_) {
                                    _onDetailClick(contact);
                                  }))
                              .toList(),
                        ),
                      ),
                    ),
                  ),

                  // 分页控件
                  Container(
                    padding: EdgeInsets.all(12.0),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8.0),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.grey.withOpacity(0.1),
                          spreadRadius: 1,
                          blurRadius: 3,
                          offset: Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(width: 16.0),
                        ElevatedButton(
                          onPressed: _start > 0 ? _handlePrev : null,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue.shade600,
                            foregroundColor: Colors.white,
                            minimumSize: Size(100, 48),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            elevation: 4,
                            textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(Icons.arrow_back),
                              SizedBox(width: 8.0),
                              Text('上一页'),
                            ],
                          ),
                        ),
                        SizedBox(width: 24.0),
                        Text(
                          '${_start + 1}-${_start + _contacts.length}/${_total}',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.grey.shade700,
                          ),
                        ),
                        SizedBox(width: 24.0),
                        ElevatedButton(
                          onPressed: _start + _limit < _total ? _handleNext : null,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue.shade600,
                            foregroundColor: Colors.white,
                            minimumSize: Size(100, 48),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            elevation: 4,
                            textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text('下一页'),
                              SizedBox(width: 8.0),
                              Icon(Icons.arrow_forward),
                            ],
                          ),
                        ),
                        SizedBox(width: 40.0),
                        SizedBox(
                          width: 120,
                          child: TextField(
                            controller: TextEditingController(text: (_start ~/ _limit + 1).toString()),
                            onChanged: _handlePageChange,
                            onSubmitted: (value) => _jump(),
                            keyboardType: TextInputType.number,
                            decoration: InputDecoration(
                              labelText: '页码',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                              contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0),
                            ),
                          ),
                        ),
                        SizedBox(width: 16.0),
                        ElevatedButton(
                          onPressed: _jump,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green.shade600,
                            foregroundColor: Colors.white,
                            minimumSize: Size(100, 48),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            elevation: 4,
                            textStyle: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                          ),
                          child: Text('跳转到'),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}